package com.finger.forest;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureCollection;
import com.esri.arcgisruntime.data.FeatureCollectionTable;
import com.esri.arcgisruntime.data.FeatureQueryResult;
import com.esri.arcgisruntime.data.QueryParameters;
import com.esri.arcgisruntime.data.ServiceFeatureTable;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.PointCollection;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.layers.FeatureCollectionLayer;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.Renderer;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleRenderer;
import com.esri.arcgisruntime.symbology.UniqueValueRenderer;
import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseApi;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.base.SystemConfig;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.PatrolTrailModel;
import com.finger.forest.model.WorkLogModel;
import com.finger.forest.utils.ClickUtils;
import com.finger.forest.utils.DateUtil;
import com.finger.forest.utils.ToastUtils;
import com.finger.forest.utils.encode.PrefsUtil;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 巡护轨迹
 */
public class PatrolTraillActivity extends BaseActivity<RegisterPresenter> implements BaseView {

    private static final String TAG = "PatrolTraillActivity";

    /**
     * 返回
     */
    @BindView(R.id.btn_back)
    ImageView backIv;

    /**
     * 开始时间
     */
    @BindView(R.id.tv_start_time)
    TextView startTimeTv;

    /**
     * 结束时间
     */
    @BindView(R.id.tv_end_time)
    TextView endTimeTv;

    /**
     * 责任区ID
     */
    String areaId;

    private MapView mMapView;

    private Calendar calendar;
    private DatePickerDialog dialog;

    private Calendar selectedDate;
    private Calendar startDate;
    private Calendar endDate;

    @Override
    protected int setView() {
        return R.layout.activity_patrol_trail;
    }

    @Override
    protected void receiveData() {

    }

    @Override
    protected void initializeView() {
        //获取责任区ID
        areaId = PrefsUtil.getString(PatrolTraillActivity.this,CommonKey.AREA_ID);

        //设置证书
        //ArcGISRuntimeEnvironment.setLicense("");
        mMapView = findViewById(R.id.mapView);

        //初始化地图
        setupMap();

        //添加巡护线路
        addLineLayer();
        //添加巡查点
        addPointLayer();

        Date date = new Date();
        //查询巡护轨迹
        queryPatrolTrail(DateUtil.dateToStr(date), DateUtil.dateToStr(date));

        selectedDate = Calendar.getInstance();
        startDate = Calendar.getInstance();
        endDate = Calendar.getInstance();

        //正确设置方式 原因：注意事项有说明
        startDate.set(2018, 0, 1);
        endDate.set(2040, 0, 1);

        //初始化查询日期
        startTimeTv.setText(DateUtil.dateToStr(DateUtil.DATE_FORMAT));
        endTimeTv.setText(DateUtil.dateToStr(DateUtil.DATE_FORMAT));

    }

    @Override
    protected void loadDataFromServer() {

    }

    private void setupMap() {
        if (mMapView != null) {
            ArcGISRuntimeEnvironment.setLicense(CommonKey.LICENSE);
            mMapView.setAttributionTextVisible(false);
            Basemap.Type basemapType = Basemap.Type.IMAGERY;
            ArcGISMap map = new ArcGISMap(basemapType, SystemConfig.latitude, SystemConfig.longitude, SystemConfig.mapLevel);
            mMapView.setMap(map);

            //添加巡护线路图层
            mMapView.getMap().getOperationalLayers().add(0, featureLayerLine);
            //添加巡护标识图层
            mMapView.getMap().getOperationalLayers().add(1, featureLayer);
        }
    }

    //线图层添加
    ServiceFeatureTable serviceFeatureTableLine = new ServiceFeatureTable(BaseApi.GIS_SERVER_URL + BaseApi.GIS_POLYLINE);
    FeatureCollectionLayer featureLayerLine = new FeatureCollectionLayer(new FeatureCollection());
    private void addLineLayer() {
        //线图层样式
        SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, getResources().getColor(R.color.colorYellow), 2);
        SimpleRenderer lineRenderer = new SimpleRenderer(lineSymbol);

        QueryParameters queryParams = new QueryParameters();
        queryParams.setWhereClause("BelongArea = "+ areaId);

        final ListenableFuture<FeatureQueryResult> queryResult = serviceFeatureTableLine.queryFeaturesAsync(queryParams);
        queryResult.addDoneListener(() -> {
            try {
                // call get on the future to get the result
                FeatureQueryResult result = queryResult.get();

                //create a feature collection table from the query results
                FeatureCollectionTable featureCollectionTable = new FeatureCollectionTable(result);
                featureCollectionTable.setRenderer(lineRenderer);

                //create a feature collection from the above feature collection table
                FeatureCollection featureCollection = new FeatureCollection();
                featureCollection.getTables().add(featureCollectionTable);

                //create a feature collection layer
                featureLayerLine = new FeatureCollectionLayer(featureCollection);

                //add the layer to the operational layers array
                mMapView.getMap().getOperationalLayers().set(0,featureLayerLine);

                // check there are some results
                Iterator<Feature> resultIterator = result.iterator();
                if (resultIterator.hasNext()) {
                    // get the extent of the first feature in the result to zoom to
                    Feature feature = resultIterator.next();
                    Envelope envelope = feature.getGeometry().getExtent();
                    //定位到巡护线路
                    mMapView.setViewpointGeometryAsync(envelope, 10);
                } else {
                    Toast.makeText(PatrolTraillActivity.this, "未查询到巡护线路", Toast.LENGTH_LONG).show();
                }

            } catch (InterruptedException | ExecutionException e) {
                Log.e(TAG, "Error in FeatureQueryResult: " + e.getMessage());
            }
        });
    }

    //点图层添加
    ServiceFeatureTable serviceFeatureTable = new ServiceFeatureTable(BaseApi.GIS_SERVER_URL + BaseApi.GIS_POINT);
    FeatureCollectionLayer featureLayer = new FeatureCollectionLayer(new FeatureCollection());
    private void addPointLayer() {
        //点图层样式
        SimpleMarkerSymbol pointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, getResources().getColor(R.color.colorWhite), 8.0f);
        pointSymbol.setOutline(new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, getResources().getColor(R.color.colorYellow), 1.5f));
        SimpleRenderer pointRenderer = new SimpleRenderer(pointSymbol);

        QueryParameters queryParams = new QueryParameters();
        queryParams.setWhereClause("BelongArea = "+ areaId);

        final ListenableFuture<FeatureQueryResult> queryResult = serviceFeatureTable.queryFeaturesAsync(queryParams);
        queryResult.addDoneListener(() -> {
            try {
                // call get on the future to get the result
                FeatureQueryResult result = queryResult.get();

                //create a feature collection table from the query results
                FeatureCollectionTable featureCollectionTable = new FeatureCollectionTable(result);
                featureCollectionTable.setRenderer(pointRenderer);

                //create a feature collection from the above feature collection table
                FeatureCollection featureCollection = new FeatureCollection();
                featureCollection.getTables().add(featureCollectionTable);

                //create a feature collection layer
                featureLayer = new FeatureCollectionLayer(featureCollection);

                //add the layer to the operational layers array
                mMapView.getMap().getOperationalLayers().set(1,featureLayer);

            } catch (InterruptedException | ExecutionException e) {
                Log.e(TAG, "Error in FeatureQueryResult: " + e.getMessage());
            }
        });
    }

    /**
     * 查询巡护轨迹
     */
    private void queryPatrolTrail(String startTime, String endTime) {
        String userId = PrefsUtil.getString(this, CommonKey.USER_ID);
        Map<String, Object> maps = new HashMap<>();
        maps.put("gridUserId", userId);
        maps.put("startTime", startTime);
        maps.put("endTime", endTime);
        //maps.put("endTime", DateUtil.dateToStr(DateUtil.DATE_FORMAT));
        presenter.queryPatrolTrail(maps);
    }

    @OnClick({R.id.btn_back, R.id.tv_start_time, R.id.tv_end_time})
    public void onClick(View v) {
        if (ClickUtils.isFastClick()) { //防止重复点击
            switch (v.getId()) {

                //返回
                case R.id.btn_back:
                    finish();
                    break;

                //开始时间
                case R.id.tv_start_time:
//                    calendar = Calendar.getInstance();
//                    dialog = new DatePickerDialog(PatrolTraillActivity.this,
//                            new DatePickerDialog.OnDateSetListener() {
//
//                                @Override
//                                public void onDateSet(DatePicker view, int year,
//                                                      int monthOfYear, int dayOfMonth) {
//                                    startTimeTv.setText(year + "/" + monthOfYear + "/"
//                                            + dayOfMonth);
//                                }
//                            }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
//                    dialog.show();

                    //时间选择器
                    TimePickerView pvTimeStart = new TimePickerBuilder(PatrolTraillActivity.this, new OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            startTimeTv.setText(DateUtil.dateToStr(date));
                            DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                            try {
                                String eTime = endTimeTv.getText().toString().trim();
                                Date dateStr = format1.parse(eTime);
                                if (date.before(dateStr)) {
                                    //查询巡护轨迹
                                    queryPatrolTrail(DateUtil.dateToStr(date),eTime);
                                } else {
                                    ToastUtils.show(PatrolTraillActivity.this, "开始时间必须小于结束时间");
                                }
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                    })
                            .setDate(selectedDate)
                            .setRangDate(startDate, endDate)//起始终止年月日设定
                            .build();
                    pvTimeStart.show();
                    break;

                //结束时间
                case R.id.tv_end_time:
//                    calendar = Calendar.getInstance();
//                    dialog = new DatePickerDialog(PatrolTraillActivity.this,
//                            new DatePickerDialog.OnDateSetListener() {
//
//                                @Override
//                                public void onDateSet(DatePicker view, int year,
//                                                      int monthOfYear, int dayOfMonth) {
//                                    endTimeTv.setText(year + "/" + monthOfYear + "/"
//                                            + dayOfMonth);
//                                }
//                            }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
//                    dialog.show();

                    String sTime = startTimeTv.getText().toString().trim();
                    if (sTime.equals("") || sTime.equals("开始时间")) {
                        ToastUtils.show(PatrolTraillActivity.this, "请先选择开始时间");
                        return;
                    }

                    //时间选择器
                    TimePickerView pvTimeEnd = new TimePickerBuilder(PatrolTraillActivity.this, new OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            endTimeTv.setText(DateUtil.dateToStr(date));
                            DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                            try {
                                Date dateStr = format1.parse(sTime);
                                if (date.after(dateStr)) {
                                    //查询巡护轨迹
                                    queryPatrolTrail(sTime, DateUtil.dateToStr(date));
                                } else {
                                    ToastUtils.show(PatrolTraillActivity.this, "结束时间必须大于开始时间");
                                }
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                    })
                            .setDate(selectedDate)
                            .setRangDate(startDate, endDate)//起始终止年月日设定
                            .build();
                    pvTimeEnd.show();
                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {

        switch (tag) {

            //查询巡护轨迹
            case ResponseTag.QUERY_PATRAL_TRAIL:
                List<PatrolTrailModel> patrolTrailModelList = (List<PatrolTrailModel>) model;
                //地图显示巡护轨迹
                showPatrolTrail(patrolTrailModelList);
                break;

            default:
                break;
        }
    }

    /**
     * 显示巡护轨迹
     *
     * @param list
     */
    private void showPatrolTrail(List<PatrolTrailModel> list) {
        GraphicsOverlay overlay = new GraphicsOverlay();
        mMapView.getGraphicsOverlays().clear();
        mMapView.getGraphicsOverlays().add(overlay);
        //添加巡护线路
        SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, getResources().getColor(R.color.colorGreen), 2);
        overlay.getGraphics().add(new Graphic(createPolyline(list), lineSymbol));
    }

    private Polyline createPolyline(List<PatrolTrailModel> list) {
        //创建点集合
        PointCollection borderCAtoNV = new PointCollection(SpatialReferences.getWgs84());
        for (PatrolTrailModel patrolTrail : list) {
            double longtitude = patrolTrail.getLongitude().doubleValue();
            double latitude = patrolTrail.getLatitude().doubleValue();
            borderCAtoNV.add(longtitude, latitude);
        }
        //创建线
        Polyline polyline = new Polyline(borderCAtoNV);
        return polyline;
    }

    @Override
    public void onError(int errcode, int tag, String message) {

    }

    @Override
    public void onPause() {
        super.onPause();
        // pause MapView
        mMapView.pause();
    }

    @Override
    public void onResume() {
        super.onResume();
        // resume MapView
        mMapView.resume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // dispose MapView
        mMapView.dispose();
    }
}
